const tronWeb = require('./tronweb')
const config = require('./config')

const CID = config.contractId
let lastEnergyUsed = 0
let contract
let color = 0xff0000
let coordinate = 7010
let interval = 3 * 1000

async function buyPixel() {
  coordinate = Math.floor(Math.random() * 999999)
  try {
    const args = {
      shouldPollResponse: true,
      callValue: 20000000,
    }
    let r = await contract.buyPixels([coordinate, color]).send(args)
    if (Number(r) > 0) {
      console.log('buy pixel success:', r, coordinate, color)
    } else {
      console.log('buy pixel failed:', r, coordinate, color)
    }
    r = await tronWeb.trx.getAccountResources()
    let energyUsed = Number(r.EnergyUsed)
    if (lastEnergyUsed > 0) {
      console.log('energy used: %d, total used: %d, limit: %d', energyUsed - lastEnergyUsed, energyUsed, r.EnergyLimit)
    }
    lastEnergyUsed = energyUsed
    // coordinate++
  } catch (e) {
    console.log('buy pixel failed:', e)
  }
}

async function main() {
  contract = await tronWeb.contract().at(CID)
  setInterval(() => {
    (async function () {
      await buyPixel()
    })()
  }, interval)
}

main().then().catch(console.log)